package com.yoo.module_base.utils


import com.google.gson.Gson
import com.google.gson.JsonParser
import com.tencent.mmkv.MMKV
import java.util.*

/**
 * 本地数据的存储工具
 * */
object MMKVUtil {
    var gson: Gson? = null
        get() {
            return field ?: Gson()
        }

    var mmkv: MMKV? = null
        get() {
            return field ?: MMKV.mmkvWithID("InterProcessKV", MMKV.MULTI_PROCESS_MODE)
        }

    init {
        gson = Gson()
        mmkv = MMKV.mmkvWithID("InterProcessKV", MMKV.MULTI_PROCESS_MODE)
    }

    fun remove(vararg key: String?) {
        if (key.isNullOrEmpty()) {
            println("key is  null")
            return
        }
        if (key.size == 1) {
            mmkv?.removeValueForKey(key[0])
        }
        if (key.size > 1) {
            mmkv?.removeValuesForKeys(key)
        }
    }

    fun <T> encodeModel(key: String, model: T?) {
        if (model == null) return
        val data = gson?.toJson(model) ?: return
        mmkv?.encode(key, data)
    }

    inline fun <reified T> decodeModel(key: String): T? {
        val data = mmkv?.decodeString(key)
        if (data.isNullOrEmpty()) return null
        return gson?.fromJson<T>(data, T::class.java)
    }

    fun <T> encodeListModel(key: String?, list: List<T>?) {
        if (list.isNullOrEmpty()) return
        val data = gson?.toJson(list)
        if (data.isNullOrEmpty()) return
        mmkv?.encode(key, data)
    }


    fun <T> decodeListModel(key: String, cls: Class<T>): List<T>? {
        val json = mmkv?.decodeString(key)
        if (json.isNullOrEmpty()) return null
//        println("取：List<T> : $json")
        val mList: MutableList<T> = ArrayList()
        val array = JsonParser().parse(json).asJsonArray
        val mGson = Gson()
        for (elem in array) {
            mList.add(mGson.fromJson(elem, cls))
        }
        return mList
    }
}




